package com.zzx.boot.filter;

import com.alibaba.fastjson.JSON;
import com.zzx.boot.common.BaseContext;
import com.zzx.boot.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * javaweb的拦截器
 * 1 ,在启动类上添加 ServerComponentScan Server 组件扫描
 * 2 ,创建一个类继承 Filter 接口 javaweb的
 * 3 ,在这个类上添加WebFilter注解
 * 4 ,
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//    路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
//    当拦截器拦截到,会执行以下方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletrequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletresponse1 = (HttpServletResponse) servletResponse;
//        log.info("拦截到的请求: {}",servletrequest1.getRequestURI());
        String requestURI = servletrequest1.getRequestURI();
//        定义一个拦截的路径
        String[] Exdlude = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
                "/front/**",
            "/common/**",
            "/user/login",
           "/user/sendMsg"
        };
//        ! 判断该路径是否需要处理
        if (math(Exdlude,requestURI)){
//            直接放行
            filterChain.doFilter(servletrequest1,servletresponse1);
            return;
        }
//        如果需要处理
        //判断session是否存在

            if (servletrequest1.getSession().getAttribute("employee")!=null){
            BaseContext.setCurrentId((Long) servletrequest1.getSession().getAttribute("employee"));
//                登录状态,直接放行
                filterChain.doFilter(servletrequest1,servletresponse1);
                return;
            }
            if ( servletrequest1.getSession().getAttribute("user")!=null){
                BaseContext.setCurrentId((Long) servletrequest1.getSession().getAttribute("user"));
                filterChain.doFilter(servletrequest1,servletresponse1);
                return;
            }
//

            //如果都不符合,那就是未登录
            //给浏览器响应数据
        servletresponse1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配器
     * @param url 要匹配的路径数组
     * @param uri 要匹配的路径
     * @return 返回是否匹配成功
     */
    public static boolean math(String[] url,String uri){
        for (String u : url) {
            boolean match = PATH_MATCHER.match(u, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
